package com.ugoodtech.mdcc.client.service.impl;

import com.drew.lang.StringUtil;
import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.VstarServiceReportService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.VstarCustomerSatisfactionReport.StatCustomerReport;
import com.ugoodtech.mdcc.core.domain.VstarCustomerSatisfactionReport.responseVo;
import com.ugoodtech.mdcc.core.domain.VstarServiceReport.*;
import com.ugoodtech.mdcc.core.dto.ServiceStatChartListResponse;
import com.ugoodtech.mdcc.core.dto.ServiceStatChartResponse;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.ServiceReportService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class VstarServiceReportServiceImpl implements VstarServiceReportService {

    private static final Logger logger = LoggerFactory.getLogger(VstarServiceReportServiceImpl.class);

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private ServiceReportRecorderRepository serviceReportRecorderRepository;

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private UserRepository userRepository;

    private Integer countPerson = 0;

    @Autowired
    private ServiceReportService serviceReportService;

    @Autowired
    private DepartmentRepository departmentRepository;

    private List<String[]> otherCustomerStatList = new ArrayList<>();

    private List<String[]> otherCustomerTypeList = new ArrayList<>();

    private List<String[]> otherPaintBrandList = new ArrayList<>();

    private List<String[]> otherMaintainBigProblem = new ArrayList<>();

    private List<String[]> otherStationAppeal = new ArrayList<>();

    ///////////////////////////////改////////////////////////////////////////


    //统计常规服务报告
    @Override
    public VstarServiceReport statReport(String province, String brand, String category, String name,
                                         Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, Long serviceType,
                                         Integer serviceNum, String userName, String isFollowUp, String followType, Long userId,
                                         Long customerStat, Long customerType, String paintBrand, String productPosition) {
        List<StationReport> reports = getStationReport(province, brand, category, name, serviceStartTime, serviceEndTime, startTime, endTime, serviceType,
                serviceNum, userName, isFollowUp, followType, userId, customerStat, customerType, paintBrand, productPosition);
        if (reports == null) {
            return null;
        }
        List<StationReport> reportList = new ArrayList<>();
        for (StationReport stationReport : reports) {
            StationRegularServiceReport answer = stationRegularServiceReportRepository.selectAnswer(stationReport.getId(), 354L);
            if (null == answer) {
                reportList.add(stationReport);
            }
        }
        otherCustomerStatList = new ArrayList<>();
        otherCustomerTypeList = new ArrayList<>();
        otherPaintBrandList = new ArrayList<>();
        otherMaintainBigProblem = new ArrayList<>();
        otherStationAppeal = new ArrayList<>();
        countPerson = reportList.size();
        logger.info("查出的常规服务报告有：" + countPerson + "份");
        VstarServiceReport vstarServiceReport = new VstarServiceReport();
        vstarServiceReport.setCountPerson(countPerson);
        //销售区域
        vstarServiceReport.setProvinceLsit(getProvinceList(reportList));
        //客户状态
        vstarServiceReport.setCustomerStatList(getCustomerStatList(reportList));
        //其他客户状态
        vstarServiceReport.setOthercustomerStatList(otherCustomerStatList);
        //客户类型
        vstarServiceReport.setCustomerTypeList(getCustomerTypeList(reportList));
        //其他客户类型
        vstarServiceReport.setOtherCustomerTypeList(otherCustomerTypeList);
        //统计维修站
        vstarServiceReport.setVstarServiceReport_serviceType(getServiceType(reportList));
        if (StringUtils.isNotEmpty(brand) && StringUtils.isEmpty(category)) {
            Integer IBS = 0;
            Integer BPC = 0;
            Integer FBS = 0;
            Integer DEALERS = 0;
            String[] brandArray = brand.split(",");
            Map<String, Integer> countBrandMap = new HashMap<>();
            List<String[]> brandStr = new ArrayList<>();
            List<String[]> otherBrandArray = new ArrayList<>();
            Map<String, Integer> otherCountBrandMap = new HashMap<>();
            for (StationReport stationReport : reportList) {
                for (String brandName : brandArray) {
                    if (StringUtils.isNotEmpty(brandName)) {
                        if (stationReport.getStation().getCategory().equals(Constants.FOR_S) && stationReport.getStation().getBrand().indexOf(brandName) != -1) {
                            if (countBrandMap.containsKey(brandName)) {
                                Integer value = countBrandMap.get(brandName);
                                countBrandMap.put(brandName, value + 1);
                            } else {
                                countBrandMap.put(brandName, 1);
                            }
                        }
                    }
                }
                if (stationReport.getStation().getCategory().equals(Constants.IBS)) {
                    String[] brandName = stationReport.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    IBS += 1;
                }
                if (stationReport.getStation().getCategory().equals(Constants.BPC)) {
                    String[] brandName = stationReport.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    BPC += 1;
                }
                if (stationReport.getStation().getCategory().equals(Constants.FBS)) {
                    String[] brandName = stationReport.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    FBS += 1;
                }
                if (stationReport.getStation().getCategory().equals(Constants.DEALERS)) {
                    String[] brandName = stationReport.getStation().getBrand().split(",");
                    for (String stationBrand : brandName) {
                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(stationBrand);
                        if (answerOption == null) {
                            if (otherCountBrandMap.containsKey(stationBrand)) {
                                Integer value = countBrandMap.get(stationBrand);
                                otherCountBrandMap.put(stationBrand, value + 1);
                            } else {
                                otherCountBrandMap.put(stationBrand, 1);
                            }
                        }
                    }
                    DEALERS += 1;
                }
            }
            String[] str = new String[2];
            for (Map.Entry<String, Integer> entry : countBrandMap.entrySet()) {
                str = new String[2];
                str[0] = entry.getKey();
                str[1] = entry.getValue().toString();
                brandStr.add(str);
            }
            if (IBS != 0) {
                str = new String[2];
                str[0] = Constants.IBS;
                str[1] = String.valueOf(IBS);
                brandStr.add(str);
            }
            if (BPC != 0) {
                str = new String[2];
                str[0] = Constants.BPC;
                str[1] = String.valueOf(BPC);
                brandStr.add(str);
            }
            if (FBS != 0) {
                str = new String[2];
                str[0] = Constants.FBS;
                str[1] = String.valueOf(FBS);
                brandStr.add(str);
            }
            if (DEALERS != 0) {
                str = new String[2];
                str[0] = Constants.DEALERS;
                str[1] = String.valueOf(DEALERS);
                brandStr.add(str);
            }
            for (Map.Entry<String, Integer> entry : otherCountBrandMap.entrySet()) {
                String[] otherBrand = new String[2];
                otherBrand[0] = entry.getKey();
                otherBrand[1] = entry.getValue().toString();
                otherBrandArray.add(otherBrand);
            }
            VstarServiceReport_Brand vstarServiceReport_brand = new VstarServiceReport_Brand();
            vstarServiceReport_brand.setBrandArray(brandStr);
            vstarServiceReport_brand.setOtherBrandList(otherBrandArray);
            vstarServiceReport_brand.setCountPerson(countPerson);
            vstarServiceReport.setVstarServiceReport_brand(vstarServiceReport_brand);
        } else {
            if (StringUtils.isNotEmpty(brand)) {
                String[] brandArray = brand.split(",");
                vstarServiceReport.setVstarServiceReport_brand(getBrand(brandArray, reportList));
            } else {
                vstarServiceReport.setVstarServiceReport_brand(getBrand(null, reportList));
            }

        }
        //油漆品牌
        vstarServiceReport.setPaintBrandList(getPaintBrandList(reportList));
        //其他油漆品牌
        vstarServiceReport.setOtherPaintBrandList(otherPaintBrandList);
        //品牌定位
        vstarServiceReport.setProductPositionList(getProductPositionList(reportList));
        //该维修站目前钣喷维修流程中面对最大问题
        vstarServiceReport.setMaintainBigProblem(getMaintainBigProblemList(reportList));
        //其他该维修站目前钣喷维修流程中面对最大问题
        vstarServiceReport.setOtherMaintainBigProblem(otherMaintainBigProblem);
        //该维修站的主要诉求
        vstarServiceReport.setStationAppeal(getStationAppeal(reportList));
        //其他该维修站的主要诉求
        vstarServiceReport.setOtherStationAppeal(otherStationAppeal);
        //统计服务目标
        vstarServiceReport.setVstarServiceReport_target(getTarget(reportList));
        //统计服务结果
        vstarServiceReport.setVstarServiceReport_results(getResults(reportList));
        return vstarServiceReport;
    }

    //将Map转List
    private List<String[]> toListStringArray(Map<String, Integer> map) {
        List<String[]> strList = new ArrayList<>();
        String[] str = new String[2];
        String[] otherStr = null;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getKey().indexOf("其他") != -1) {
                otherStr = new String[2];
                otherStr[0] = entry.getKey();
                otherStr[1] = entry.getValue().toString();
            } else {
                str = new String[2];
                str[0] = entry.getKey();
                str[1] = entry.getValue().toString();
                strList.add(str);
            }
        }
        if (otherStr != null) {
            strList.add(otherStr);
        }
        return strList;
    }

    private String getStationColorReport_AnswerOther(StationReport stationReport, Long questionId) {
        if (stationReport.getStation() != null && stationReport.getStation().getId() != null && stationReport.getStation().getId() != 0) {
            Long stationId = stationReport.getStation().getId();
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.station.id.eq(stationId));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            StationReport report = stationReportRepository.findOne(builder);
            if (report == null) {
                return null;
            }
            StationColorReport colorReport = stationColorReportRepository.selectReport(report.getId(), questionId);
            if (colorReport != null && StringUtils.isNotEmpty(colorReport.getAnswerOther())) {
                return colorReport.getAnswerOther();
            }
        }
        return null;
    }

    //销售区域
    private List<String[]> getProvinceList(List<StationReport> reports) {
        Map<String, Integer> provinceMap = new HashMap<>();
        for (StationReport stationReport : reports) {
            if (StringUtils.isNotEmpty(stationReport.getStation().getProvince())) {
                String province = stationReport.getStation().getProvince();
                if (provinceMap.containsKey(province)) {
                    Integer value = provinceMap.get(province);
                    provinceMap.put(province, value + 1);
                } else {
                    provinceMap.put(province, 1);
                }
            }
        }
        return toListStringArray(provinceMap);
    }

    //客户状态
    private List<String[]> getCustomerStatList(List<StationReport> reports) {
        Map<String, Integer> customerStatMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport stationReport : reports) {
            if (stationReport.getStation().getCustomerStat() != null && stationReport.getStation().getCustomerStat() != 0) {
                Long customerStatId = stationReport.getStation().getCustomerStat();
                answerOption = questionAnswerOptionRepository.findOne(customerStatId);
                if (customerStatMap.containsKey(answerOption.getName())) {
                    Integer value = customerStatMap.get(answerOption.getName());
                    customerStatMap.put(answerOption.getName(), value + 1);
                } else {
                    customerStatMap.put(answerOption.getName(), 1);
                }
                if (customerStatId == 362L) {
                    // todo 其他客户状态
                    String answer = getStationColorReport_AnswerOther(stationReport, 184L);
                    if (answer == null) {
                        continue;
                    }
                    if (otherMap.containsKey(answer)) {
                        Integer value = otherMap.get(answer);
                        otherMap.put(answer, value + 1);
                    } else {
                        otherMap.put(answer, 1);
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherCustomerStatList = toListStringArray(otherMap);
        }
        return toListStringArray(customerStatMap);
    }


    //客户类型
    private List<String[]> getCustomerTypeList(List<StationReport> reports) {
        Map<String, Integer> customerTypeMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport stationReport : reports) {
            if (stationReport.getStation().getCustomerType() != null && stationReport.getStation().getCustomerType() != 0) {
                Long customerTypeId = stationReport.getStation().getCustomerType();
                answerOption = questionAnswerOptionRepository.findOne(customerTypeId);
                if (customerTypeMap.containsKey(answerOption.getName())) {
                    Integer value = customerTypeMap.get(answerOption.getName());
                    customerTypeMap.put(answerOption.getName(), value + 1);
                } else {
                    customerTypeMap.put(answerOption.getName(), 1);
                }
                if (customerTypeId == 366L) {
                    // todo 其他客户类型
                    String answer = getStationColorReport_AnswerOther(stationReport, 185L);
                    if (answer == null) {
                        continue;
                    }
                    if (otherMap.containsKey(answer)) {
                        Integer value = otherMap.get(answer);
                        otherMap.put(answer, value + 1);
                    } else {
                        otherMap.put(answer, 1);
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherCustomerTypeList = toListStringArray(otherMap);
        }
        return toListStringArray(customerTypeMap);
    }

    //油漆品牌
    private List<String[]> getPaintBrandList(List<StationReport> reports) {
        Map<String, Integer> paintBrandMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport stationReport : reports) {
            if (StringUtils.isNotEmpty(stationReport.getStation().getPaintBrand())) {
                String[] paintBrandids = stationReport.getStation().getPaintBrand().split(",");
                for (String id : paintBrandids) {
                    answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (answerOption != null&&answerOption.getName()!=null) {
                        if (paintBrandMap.containsKey(answerOption.getName())) {
                            Integer value = paintBrandMap.get(answerOption.getName());
                            paintBrandMap.put(answerOption.getName(), value + 1);
                        } else {
                            paintBrandMap.put(answerOption.getName(), 1);
                        }
                    }
                    if (id.equals("280")) {
                        //todo 其他的油漆品牌
                        String answer = getStationColorReport_AnswerOther(stationReport, 13L);
                        if (answer == null) {
                            continue;
                        }
                        if (otherMap.containsKey(answer)) {
                            Integer value = otherMap.get(answer);
                            otherMap.put(answer, value + 1);
                        } else {
                            otherMap.put(answer, 1);
                        }
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherPaintBrandList = toListStringArray(otherMap);
        }
        return toListStringArray(paintBrandMap);
    }

    //品牌定位
    private List<String[]> getProductPositionList(List<StationReport> reports) {
        Map<String, Integer> productPositionMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport stationReport : reports) {
            if (StringUtils.isNotEmpty(stationReport.getStation().getProductPosition())) {
                String[] productPositionids = stationReport.getStation().getProductPosition().split(",");
                for (String id : productPositionids) {
                    answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (answerOption != null&&answerOption.getName()!=null) {
                        if (productPositionMap.containsKey(answerOption.getName())) {
                            Integer value = productPositionMap.get(answerOption.getName());
                            productPositionMap.put(answerOption.getName(), value + 1);
                        } else {
                            productPositionMap.put(answerOption.getName(), 1);
                        }
                    }
                }
            }
        }
        return toListStringArray(productPositionMap);
    }

    //目前颜色准确度
    private List<String[]> getColorAccuracyList(List<StationReport> reports) {
        Map<String, Integer> colorAccuracyMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        for (StationReport report : reports) {
            // todo 目前颜色准确度
        }
        return null;
    }

    //维修站目前钣喷维修流程中面对最大问题
    private List<String[]> getMaintainBigProblemList(List<StationReport> reports) {
        Map<String, Integer> maintainBigProblemMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        StationColorReport stationColorReport = null;
        for (StationReport report : reports) {
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            builder.and(qStationReport.auditing.eq(Constants.AUDIT_TRUE));
            builder.and(qStationReport.station.id.eq(report.getStation().getId()));
            StationReport stationReport = stationReportRepository.findOne(builder);
            if (stationReport == null) {
                logger.info("ID为：" + report.getStation().getId() + "的维修站没有基础报告");
                continue;
            }
            stationColorReport = stationColorReportRepository.selectReport(stationReport.getId(), 56L);
            if (stationColorReport != null && StringUtils.isNotEmpty(stationColorReport.getAnswerId())) {
                String[] problemIds = stationColorReport.getAnswerId().split(",");
                for (String id : problemIds) {
                    if (StringUtils.isNotEmpty(id)) {
                        answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(Long.valueOf(id)));
                        if (maintainBigProblemMap.containsKey(answerOption.getName())) {
                            Integer value = maintainBigProblemMap.get(answerOption.getName());
                            maintainBigProblemMap.put(answerOption.getName(), value + 1);
                        } else {
                            maintainBigProblemMap.put(answerOption.getName(), 1);
                        }
                        if (id.equals("266")) {
                            // todo 其他面对最大问题
                            String answer = getStationColorReport_AnswerOther(stationReport, 56L);
                            if (answer == null) {
                                continue;
                            }
                            if (otherMap.containsKey(answer)) {
                                Integer value = otherMap.get(answer);
                                otherMap.put(answer, value + 1);
                            } else {
                                otherMap.put(answer, 1);
                            }
                        }
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherMaintainBigProblem = toListStringArray(otherMap);
        }
        return toListStringArray(maintainBigProblemMap);
    }

    //维修站的主要诉求
    private List<String[]> getStationAppeal(List<StationReport> reports) {
        Map<String, Integer> stationAppealMap = new HashMap<>();
        Map<String, Integer> otherMap = new HashMap<>();
        QuestionAnswerOption answerOption = null;
        StationColorReport stationColorReport = null;
        for (StationReport report : reports) {
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            builder.and(qStationReport.auditing.eq(Constants.AUDIT_TRUE));
            builder.and(qStationReport.station.id.eq(report.getStation().getId()));
            StationReport stationReport = stationReportRepository.findOne(builder);
            if (stationReport == null) {
                logger.info("ID为：" + report.getStation().getId() + "的维修站没有基础报告");
                continue;
            }
            stationColorReport = stationColorReportRepository.selectReport(stationReport.getId(), 59L);
            if (stationColorReport != null && StringUtils.isNotEmpty(stationColorReport.getAnswerId())) {
                String[] appealIds = stationColorReport.getAnswerId().split(",");
                for (String id : appealIds) {
                    if (StringUtils.isNotEmpty(id)) {
                        answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(Long.valueOf(id)));
                        if (stationAppealMap.containsKey(answerOption.getName())) {
                            Integer value = stationAppealMap.get(answerOption.getName());
                            stationAppealMap.put(answerOption.getName(), value + 1);
                        } else {
                            stationAppealMap.put(answerOption.getName(), 1);
                        }
                        if (id.equals("272")) {
                            // todo 其他主要诉求
                            String answer = getStationColorReport_AnswerOther(stationReport, 59L);
                            if (answer == null) {
                                continue;
                            }
                            if (otherMap.containsKey(answer)) {
                                Integer value = otherMap.get(answer);
                                otherMap.put(answer, value + 1);
                            } else {
                                otherMap.put(answer, 1);
                            }
                        }
                    }
                }
            }
        }
        if (!otherMap.isEmpty()) {
            otherStationAppeal = toListStringArray(otherMap);
        }
        return toListStringArray(stationAppealMap);
    }

    //统计维修站类型
    private VstarServiceReport_ServiceType getServiceType(List<StationReport> reports) {
        VstarServiceReport_ServiceType serviceType = new VstarServiceReport_ServiceType();
        Long BPC = 0L;
        Long FBS = 0L;
        Long fourS = 0L;
        Long IBS = 0L;
        Long DEALERS = 0L;
        for (StationReport report : reports) {
            if (report.getStation().getCategory().equals(Constants.BPC)) {
                BPC += 1;
            }
            if (report.getStation().getCategory().equals(Constants.FBS)) {
                FBS += 1;
            }
            if (report.getStation().getCategory().equals(Constants.FOR_S)) {
                fourS += 1;
            }
            if (report.getStation().getCategory().equals(Constants.IBS)) {
                IBS += 1;
            }
            if (report.getStation().getCategory().equals(Constants.DEALERS)) {
                DEALERS += 1;
            }
        }
        serviceType.setBPC(BPC.intValue());
        serviceType.setFBS(FBS.intValue());
        serviceType.setFourS(fourS.intValue());
        serviceType.setIBS(IBS.intValue());
        serviceType.setDEALERS(DEALERS.intValue());
        serviceType.setCountPerson(countPerson);
        return serviceType;
    }

    //统计品牌
    private VstarServiceReport_Brand getBrand(String[] brandArray, List<StationReport> reportList) {
        List<String> brandNames = new ArrayList<>();
        for (StationReport report : reportList) {
            if (report.getStation().getCategory().equals(Constants.FOR_S)) {
                String[] brandName = report.getStation().getBrand().split(",");
                for (String brand : brandName) {
                    if (brandArray != null) {
                        for (String str : brandArray) {
                            if (!brand.equals(str)) {
                                continue;
                            } else {
                                if (StringUtils.isNotEmpty(brand)) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    } else {
                        if (StringUtils.isNotEmpty(brand)) {
                            brandNames.add(brand);
                        }
                    }
                }
            } else {
                if (report.getStation().getCategory().equals(Constants.IBS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.IBS);
                }
                if (report.getStation().getCategory().equals(Constants.BPC)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.BPC);
                }
                if (report.getStation().getCategory().equals(Constants.FBS)) {
                    String[] brandName = report.getStation().getBrand().split(",");
                    for (String brand : brandName) {
                        if (brandArray != null) {
                            for (String str : brandArray) {
                                if (brand.equals(str)) {
                                    continue;
                                } else {
                                    if (StringUtils.isNotEmpty(brand)) {
                                        QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                        if (answerOption == null) {
                                            brandNames.add(brand);
                                        }
                                        break;
                                    }
                                }
                            }
                        } else {
                            if (StringUtils.isNotEmpty(brand)) {
                                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brand);
                                if (answerOption == null) {
                                    brandNames.add(brand);
                                }
                            }
                        }
                    }
                    brandNames.add(Constants.FBS);
                }
            }
        }
        return countBrand(brandNames);
    }

    private VstarServiceReport_Brand countBrand(List<String> brandNames) {
        Map<String, Integer> brandMap = new HashMap<>();
        for (String brand : brandNames) {
            if (brandMap.containsKey(brand)) {
                Integer value = brandMap.get(brand);
                brandMap.put(brand, value + 1);
            } else {
                brandMap.put(brand, 1);
            }
        }
        VstarServiceReport_Brand brand = new VstarServiceReport_Brand();
        List<String[]> brandList = new ArrayList<>();
        List<String[]> otherBrandList = new ArrayList<>();
        Map<String, Integer> otherbrandMap = new HashMap<>();
        for (Map.Entry<String, Integer> entry : brandMap.entrySet()) {
            if (entry.getKey().equals(Constants.IBS) || entry.getKey().equals(Constants.FBS) || entry.getKey().equals(Constants.BPC)) {
                continue;
            }
            String[] brandArray = new String[2];
            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(entry.getKey());
            if (answerOption != null) {
                brandArray[0] = entry.getKey();
                brandArray[1] = entry.getValue().toString();
                brandList.add(brandArray);
            } else {
                if (otherbrandMap.containsKey("其他品牌")) {
                    Integer value = otherbrandMap.get("其他品牌");
                    otherbrandMap.put("其他品牌", value + entry.getValue());
                } else {
                    otherbrandMap.put("其他品牌", entry.getValue());
                }
                String[] otherBrandArray = new String[2];
                otherBrandArray[0] = entry.getKey();
                otherBrandArray[1] = entry.getValue() + "";
                otherBrandList.add(otherBrandArray);
            }
        }
        for (Map.Entry<String, Integer> entry : brandMap.entrySet()) {
            if (entry.getKey().equals(Constants.IBS) || entry.getKey().equals(Constants.FBS) || entry.getKey().equals(Constants.BPC)) {
                String[] otherBrand = new String[2];
                otherBrand[0] = entry.getKey();
                otherBrand[1] = entry.getValue().toString();
                brandList.add(otherBrand);
            }
        }
        if (otherbrandMap != null && !otherbrandMap.isEmpty()) {
            String[] otherBrand = new String[2];
            otherBrand[0] = "其他品牌";
            otherBrand[1] = otherbrandMap.get("其他品牌").toString();
            brandList.add(otherBrand);
        }
        brand.setOtherBrandList(otherBrandList);
        brand.setBrandArray(brandList);
        brand.setCountPerson(countPerson);
        return brand;
    }


    //统计服务目标
    private VstarServiceReport_Target getTarget(List<StationReport> reports) {
        List<String> targetIdList = new ArrayList<>();
        List<StationReport> reportList = new ArrayList<>();
        for (StationReport report : reports) {
            if (StringUtils.isEmpty(report.getServiceTypAnswerIds())) {
                continue;
            }
            String[] targetIds = report.getServiceTypAnswerIds().split(",");
            for (String target : targetIds) {
                if (StringUtils.isNotEmpty(target)) {
                    targetIdList.add(target);
                    if (target.equals("191")) {
                        reportList.add(report);
                    }
                }
            }
        }
        VstarServiceReport_Target targetList = countTarget(targetIdList);
        targetList.setOtherTarget(targetOther(reportList));
        return targetList;
    }

    private VstarServiceReport_Target countTarget(List<String> targetIdList) {
        Map<Long, Integer> targetMap = new HashMap<>();
        for (String target : targetIdList) {
            if (targetMap.containsKey(Long.valueOf(target))) {
                Integer value = targetMap.get(Long.valueOf(target));
                targetMap.put(Long.valueOf(target), value + 1);
            } else {
                targetMap.put(Long.valueOf(target), 1);
            }
        }
        VstarServiceReport_Target target = new VstarServiceReport_Target();
        List<String[]> targetList = new ArrayList<>();
        for (Map.Entry<Long, Integer> entry : targetMap.entrySet()) {
            String[] targetArray = new String[2];
            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(entry.getKey());
            if (answerOption != null) {
                targetArray[0] = answerOption.getName();
                targetArray[1] = entry.getValue().toString();
                targetList.add(targetArray);
            }
        }
        target.setTarget(targetList);
        target.setCountPerson(countPerson);
        return target;
    }

    private List<String[]> targetOther(List<StationReport> reportList) {
        List<String[]> otherTargerList = new ArrayList<>();
        for (StationReport report : reportList) {
//            if (report.getServiceTypAnswerIds().indexOf("191") == -1) {
//                continue;
//            }
            StationRegularServiceReport serviceReport = stationRegularServiceReportRepository.selectQuestionOther(report.getId(), 155L);
            if (serviceReport == null) {
                continue;
            }
            String realName = "";
            if (report.getUser() != null) {
                UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
                if (userProfile != null) {
                    if (StringUtils.isNotEmpty(userProfile.getRealName())) {
                        realName = userProfile.getRealName();
                    }
                }
            }
            String[] otherTarger = new String[5];
            otherTarger[0] = report.getStation().getName();
            otherTarger[1] = report.getStation().getStationNum();
            otherTarger[2] = report.getCreationTimeStr();
            otherTarger[3] = serviceReport.getAnswerOther();
            otherTarger[4] = realName;
            otherTargerList.add(otherTarger);
        }
        return otherTargerList;
    }

    //统计服务结果
    private VstarServiceReport_Results getResults(List<StationReport> reports) {
        VstarServiceReport_Results results = new VstarServiceReport_Results();
        Long noComplete_UnableToFollowUp = 0L;
        Long noComplete_NeedToFollowUp = 0L;
        Long complete = 0L;
        Long complete_NeedOthersToFollowUp = 0L;
        Long plan = 0L;
        for (StationReport report : reports) {
            noComplete_UnableToFollowUp += (Long) stationRegularServiceReportRepository.count(179L, report.getId());
            noComplete_NeedToFollowUp += (Long) stationRegularServiceReportRepository.count(180L, report.getId());
            complete += (Long) stationRegularServiceReportRepository.count(181L, report.getId());
            complete_NeedOthersToFollowUp += (Long) stationRegularServiceReportRepository.count(182L, report.getId());
            plan += (Long) stationRegularServiceReportRepository.count(354L, report.getId());
        }
        List<VstarServiceReport_CompleteFollowUp> completeFollowUps = new ArrayList<>();
        List<VstarServiceReport_UnFinshedNoFollowUp> unFinshedNoFollowUps = new ArrayList<>();
        List<VstarServiceReport_UnFinshedFollowUp> unFinshedFollowUps = new ArrayList<>();
        for (StationReport report : reports) {
            UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
            QStationRegularServiceReport regularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(regularServiceReport.deleted.eq(false));
            builder.and(regularServiceReport.stationReport.id.eq(report.getId()));
            builder.and(regularServiceReport.questionId.eq(156L));
            builder.and(regularServiceReport.answerId.ne("181"));
            StationRegularServiceReport serviceReport = stationRegularServiceReportRepository.findOne(builder);
            if (serviceReport != null) {
                if (Long.valueOf(serviceReport.getAnswerId()) == 179L) {
                    VstarServiceReport_CompleteFollowUp completeFollowUp = new VstarServiceReport_CompleteFollowUp();
                    completeFollowUp.setStationName(report.getStation().getName());
                    completeFollowUp.setStationNum(report.getStation().getStationNum());
                    completeFollowUp.setCreateTime(report.getCreationTimeStr());
                    completeFollowUp.setId(report.getId());
                    completeFollowUp.setUserName(userProfile.getRealName());
                    completeFollowUp.setAnswer(serviceReport.getAnswerOther());
                    completeFollowUps.add(completeFollowUp);
                }
                if (Long.valueOf(serviceReport.getAnswerId()) == 180L) {
                    VstarServiceReport_UnFinshedNoFollowUp unFinshedNoFollowUp = new VstarServiceReport_UnFinshedNoFollowUp();
                    unFinshedNoFollowUp.setStationName(report.getStation().getName());
                    unFinshedNoFollowUp.setStationNum(report.getStation().getStationNum());
                    unFinshedNoFollowUp.setCreateTime(report.getCreationTimeStr());
                    unFinshedNoFollowUp.setId(report.getId());
                    unFinshedNoFollowUp.setUserName(userProfile.getRealName());
                    unFinshedNoFollowUp.setAnswer(serviceReport.getAnswerOther());
                    unFinshedNoFollowUps.add(unFinshedNoFollowUp);
                }
                if (Long.valueOf(serviceReport.getAnswerId()) == 182L) {
                    VstarServiceReport_UnFinshedFollowUp unFinshedFollowUp = new VstarServiceReport_UnFinshedFollowUp();
                    unFinshedFollowUp.setStationName(report.getStation().getName());
                    unFinshedFollowUp.setStationNum(report.getStation().getStationNum());
                    unFinshedFollowUp.setCreateTime(report.getCreationTimeStr());
                    unFinshedFollowUp.setId(report.getId());
                    if (userProfile != null) {
                        unFinshedFollowUp.setUserName(userProfile.getRealName());
                    } else {
                        unFinshedFollowUp.setUserName("");
                    }
                    if (StringUtils.isNotEmpty(report.getDeparmentIds())) {
                        String[] departmentIds = report.getDeparmentIds().split(",");
                        StringBuffer stringBuffer = new StringBuffer("");
                        for (String id : departmentIds) {
                            if (StringUtils.isNotEmpty(id)) {
                                Department department = departmentRepository.findOne(Long.valueOf(id));
                                if (department != null && StringUtils.isNotEmpty(department.getName())) {
                                    stringBuffer.append(department.getName() + ",");
                                }
                            }
                        }
                        unFinshedFollowUp.setAnswer(stringBuffer.toString());
                    }
                    unFinshedFollowUps.add(unFinshedFollowUp);
                }
            }
        }
        results.setPlan(plan.intValue());
        results.setCompleteFollowUps(completeFollowUps);
        results.setUnFinshedNoFollowUps(unFinshedNoFollowUps);
        results.setUnFinshedFollowUps(unFinshedFollowUps);
        results.setNoComplete_UnableToFollowUp(noComplete_UnableToFollowUp.intValue());
        results.setNoComplete_NeedToFollowUp(noComplete_NeedToFollowUp.intValue());
        results.setComplete(complete.intValue());
        results.setComplete_NeedOthersToFollowUp(complete_NeedOthersToFollowUp.intValue());
        results.setCountPerson(noComplete_UnableToFollowUp.intValue() + noComplete_NeedToFollowUp.intValue() + complete.intValue() + complete_NeedOthersToFollowUp.intValue());
        return results;
    }


    //筛选条件
    @Override
    public List<StationReport> getStationReport(String provinces, String brand, String category, String name,
                                                Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, Long serviceType,
                                                Integer serviceNum, String userName, String isFollowUp, String followType, Long userId,
                                                Long customerStat, Long customerType, String paintBrand, String productPosition) {
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
//        builder.and(qStationReport.station.checkStation.eq(true));

        /**
         * 判断是否是经销商
         * 经销商：拿出经销商绑定的维修站ID 进行筛选
         * 内部人员：拿出绑定的省份 进行筛选
         */
        User user = userRepository.findOne(userId);
        UserProfile userProfile = userProfileRepository.findByUserId(userId);
        if (userProfile == null) {
            return null;
        }
        if (StringUtils.isNotEmpty(provinces)) {
            String[] province = provinces.split(",");
            builder.and(qStationReport.station.province.in(province));
        } else if (user.getUserType().equals(UserType.dealers)) {
            List<Station> stationList = userProfile.getDepartmentList().get(0).getStationList();
            Long[] stationIds = new Long[stationList.size()];
            for (int i = 0; i < stationList.size(); i++) {
                stationIds[i] = stationList.get(i).getId();
            }
            builder.and(qStationReport.station.id.in(stationIds));
        } else {
            List<Nation> nationList = userProfile.getNationList();
            String[] provinceArray = new String[nationList.size()];
            for (int i = 0; i < nationList.size(); i++) {
                provinceArray[i] = nationList.get(i).getProvince();
            }
            builder.and(qStationReport.station.province.in(provinceArray));
        }

        if (customerStat != null && customerStat != 0) {
            builder.and(qStationReport.station.customerStat.eq(customerStat));
        }
        if (customerType != null && customerType != 0) {
            builder.and(qStationReport.station.customerType.eq(customerType));
        }
        if (StringUtils.isNotEmpty(paintBrand)) {
            builder.and(qStationReport.station.paintBrand.like("%" + paintBrand + "%"));
        }
        if (StringUtils.isNotEmpty(productPosition)) {
            builder.and(qStationReport.station.productPosition.like("%" + productPosition + "%"));
        }
        if (StringUtils.isNotEmpty(brand)) {
            String[] brandArray = brand.split(",");
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (int i = 0; i < brandArray.length; i++) {
                orBuilder.or(qStationReport.station.brand.like("%" + brandArray[i] + "%"));
            }
            builder.and(orBuilder);
        }
        if (StringUtils.isNotEmpty(category)) {
            builder.and(qStationReport.station.category.eq(category));
        }
        if (StringUtils.isNotEmpty(name)) {
            builder.and(qStationReport.station.name.like("%" + name + "%"));
        }
        if (serviceType != null && serviceType != 0) {
            builder.and(qStationReport.serviceTypAnswerIds.like("%" + serviceType + "%"));
        }
        if (serviceNum != null && serviceNum != 0) {
            builder.and(qStationReport.user.serviceNum.eq(serviceNum));
        }
        if (StringUtils.isNotEmpty(userName)) {
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            List<UserProfile> userProfiles = (List<UserProfile>) userProfileRepository.findAll();
            Long[] userIds = new Long[userProfiles.size() + 1];
            for (int i = 0; i < userProfiles.size(); i++) {
                userIds[i] = userProfiles.get(i).getUser().getId();
            }
            if (userId != null) {
                userIds[userProfiles.size()] = userId;
            }
            builder.and(qStationReport.user.id.in(userIds));
        }

        if (serviceStartTime != null && serviceStartTime != 0 && serviceEndTime != null && serviceEndTime != 0) {
            builder.and(qStationReport.startServiceTime.after(new Date(serviceStartTime)));
            builder.and(qStationReport.endServiceTime.before(new Date(serviceEndTime)));
        }

        if (startTime != null && startTime != 0 && endTime != null && endTime != 0) {
            builder.and(qStationReport.creationTime.after(new Date(startTime)));
            builder.and(qStationReport.creationTime.before(new Date(endTime)));
        }

        List<StationReport> reports = (List<StationReport>) stationReportRepository.findAll(builder);
        return reports;
    }

    @Override
    public com.ugoodtech.mdcc.core.dto.JsonResponse getServiceChart(User user, String province, String city, String brand, String category, String stationName,
                                                                    Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, String serviceType,
                                                                    Integer serviceNum, String reportStatus,String userName, Boolean type, String serviceReportStatus, Long userId, Boolean paintType,
                                                                    String customerStat, String customerType, String paintBrand, String productPosition, String stationNum, String department,String payService,String sentTime,String serviceTime) {
        com.ugoodtech.mdcc.core.dto.JsonResponse jsonResponse = serviceReportService.getServiceChart(user, province,city, brand, category, stationName,
                serviceStartTime, serviceEndTime, startTime, endTime, serviceType, serviceNum,reportStatus,
                userName, type, serviceReportStatus,userId,paintType, customerStat, customerType,
                paintBrand, productPosition, stationNum, department,payService,sentTime,serviceTime);
        return jsonResponse;
    }


}
